<?php
/*
 * This file is part of phpep.
 * 
 * phpep
 * 
 * Copyright (C) 2007 Andrés Otárola Alvarado pgugged/cast -- otarola.andres@gmail.com
 * 
 * phpep is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * phpep is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *    
 */
require_once 'Connection.class.php';
require_once APP_DIR.'core/DbAdapter.interface.php';

class MySqlDb  extends Connection implements DbAdapter{

    function __construct($autoConnect = true) {
    	parent::__construct();
    	if($autoConnect)
    		$this->connect();
    }
    function __destruct(){
    	$this->disconnect();
    }
    public function get_primary_keys($table_name){
    	$res = $this->query("desc {$table_name}");
    	while($row = $this->fetch_array($res)){
    		if($row['Key'] == 'PRI'){
    			$tmp[] = $row['Field'];
    		}
    	}
    	return $tmp;    	
    }
    public function call_stored_procedure($sp_routine){
    	$this->query("CALL {$sp_routine}");
    }    
    public function get_table_fields($table_name){
    	$res = $this->query("desc {$table_name}");
    	while($row = $this->fetch_array($res)){
    		$fields[] = $row['Field'];
    	}
    	return $fields;
    }
    public function connect(){
    	$this->link = mysql_connect(
    		$this->dataConnection->getHost(),
    		$this->dataConnection->getUser(),
    		$this->dataConnection->getPass(),
    		$this->link) or die('Error de conexion a la base de datos');
    	mysql_select_db($this->dataConnection->getSchema());
    }
    
    public function errno(){
    	return mysql_errno($this->link);
    }
    
    public function error(){
    	return mysql_error($this->link);
    }
    
    public static function escape_string($string){
    	return mysql_real_escape_string($string);
    }
    
    public function query($query){
    	$res =  mysql_query($query, $this->link);
    	if(!$res) throw new Exception($this->error());
    	return $res;
    }
    
    public function fetch_array($result, $array_type = MYSQL_ASSOC){
    	return mysql_fetch_array($result, $array_type);
    }
    
    public function fetch_row($result){
    	return mysql_fetch_row($result);
    }
    
    public function fetch_object($result){
        return mysql_fetch_object($result);
    }
    
    public function num_rows($result){
        return mysql_num_rows($result);
    }
    
   	protected function disconnect(){
        return mysql_close($this->link);
    }
}
?>